package com.gitee.zycra.future.job.web.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;

/**
 * @author zycra
 */
@Slf4j
@Component
public class NodeInfoInterceptor implements HandshakeInterceptor {

    private static final String UNKNOWN = "unknown";

    private static final String APPLICATION_NAME_QUERY_KEY = "applicationName=";

    private static final String SPLIT_LABEL = "&";

    private static final String IP_KEY = "ip";

    private static final String APPLICATION_NAME_KEY = "applicationName";

    /**
     * 顺序为nginx,weblogic,apache,Squid,其他
     */
    private static final List<String> HEADERS = List.of("X-Real-IP", "WL-Proxy-Client-IP", "Proxy-Client-IP", "X-Forwarded-For", "HTTP_CLIENT_IP");

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        String ip = getRequestIp(request);
        String query = request.getURI().getQuery();
        String applicationName = getFromQuery(query, APPLICATION_NAME_QUERY_KEY);
        log.info("开始连接, ip={}, applicationName={}", ip, applicationName);
        attributes.put(IP_KEY, ip);
        attributes.put(APPLICATION_NAME_KEY, applicationName);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // do nothing
    }

    private String getRequestIp(ServerHttpRequest request) {
        for (String header : HEADERS) {
            String ipHeader = request.getHeaders().getFirst(header);
            if (ipHeader != null && !ipHeader.isBlank() && !UNKNOWN.equalsIgnoreCase(ipHeader)) {
                return ipHeader.split(",")[0];
            }
        }
        return request.getRemoteAddress().getHostName();
    }

    private String getFromQuery(String query, String key) {
        String[] params = query.split(SPLIT_LABEL);
        for (String param : params) {
            if (param.startsWith(key)) {
                return param.substring(key.length());
            }
        }
        return UNKNOWN;
    }
}
